package com.two.screen.water.balance.utils;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.os.Environment;
import android.text.TextUtils;


import com.two.screen.water.balance.ui.App;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 创建者     Noel
 * 创建时间   2019/5/15 11:29
 * 描述	      ${TODO}
 */
public class FileUtils {

    public final static int DEFAULT_FILE_OPERATE_MODE = 0;     //创建文件时File对象是绝对路径，如果存在文件则覆盖

    public final static int IGNORE_NOT_RECREATE_MODE = 1;    //创建文件时File对象是相对储存器的路径，如果存在文件则表示已经存在，不进行操作

    public final static int IGNORE_AND_RECREATE_MODE = 2;    //创建文件时File对象是相对储存器的路径，如果存在文件则表示已经存在，不进行操作

    public final static int NOT_IGNORE_RECREATE_MODE = 3;   //创建文件时File对象是绝对路径，如果存在文件则覆盖

    private final static boolean DEFAULT_IGNORE_STYLE = false;

    private final static boolean DEFAULT_AUTO_CREATE_DIRECTORY = true;   //如果目录不存在是否自动创建


    /**
     * 删除文件
     *
     * @param file
     */
    public static void deleteFile(File file) {
        if (file == null || TextUtils.isEmpty(file.getAbsolutePath())) {
            return;
        }
        if (file.exists()) {
            if (!file.isDirectory()) {
                file.delete();
                CommUtils.Companion.println("PictureFileUtils:", file.getAbsolutePath() + ",删除成功:" + file.exists());
            }
            updateFileFromDatabase(App.Companion.getContext(), file);
        }
    }

    //此方法来自网络搜索
    public static void updateFileFromDatabase(Context context, File file) {
        String[] paths = new String[]{Environment.getExternalStorageDirectory().toString()};
        MediaScannerConnection.scanFile(context, paths, null, null);
        MediaScannerConnection.scanFile(context, new String[]{file.getAbsolutePath()},
                null, (path, uri) -> CommUtils.Companion.println("PictureFileUtils:", "同步刷新媒体库：path=>" + path + ",uri:" + uri));
    }

    /**
     * @param filePath
     */
    public static void deleteFile(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            deleteFile(new File(filePath));
        }
    }

    /**
     * 删除一个目录
     *
     * @param folder
     */
    public static void deleteFolder(File folder) {
        if (folder == null || TextUtils.isEmpty(folder.getAbsolutePath())) {
            return;
        }
        if (folder.exists()) {
            if (folder.isDirectory()) {
                File[] files = folder.listFiles();
                if (files != null) {
                    for (File file : files) {
                        deleteFolder(file);
                    }
                }
            } else {
                deleteFile(folder);
            }
        }
    }

    /**
     * @param folderPath
     */
    public static void deleteFolder(String folderPath) {
        if (!TextUtils.isEmpty(folderPath)) {
            deleteFile(new File(folderPath));
        }
    }


    /**
     * 复制Assets目录下的文件到指定位置
     *
     * @param strAssetsFilePath
     * @param strDesFilePath
     * @return
     */
    public boolean assetsCopyData(String strAssetsFilePath,
                                  String strDesFilePath) {

        boolean bIsSuc = true;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        File file = new File(strDesFilePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
                Runtime.getRuntime().exec("chmod 766 " + file);
            } catch (IOException e) {
                bIsSuc = false;
            }

        } else {// 存在
            return true;
        }

        try {
            inputStream = App.Companion.getContext().getAssets().open(
                    strAssetsFilePath);
            outputStream = new FileOutputStream(file);

            int nLen = 0;

            byte[] buff = new byte[1024 * 1];
            while ((nLen = inputStream.read(buff)) > 0) {
                outputStream.write(buff, 0, nLen);
            }

        } catch (IOException e) {
            bIsSuc = false;
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }

                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                bIsSuc = false;
            }

        }

        return bIsSuc;
    }


    /**
     * 复制文件
     *
     * @param src
     * @param dst
     * @return
     * @throws IOException
     */
    public static boolean copyFile(File src, File dst) throws IOException {

        if ((!src.exists()) || src.isDirectory() || dst.isDirectory()) {
            return false;
        }
        if (!dst.exists()) {
            dst.createNewFile();
            return false;
        }
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        inputStream = new FileInputStream(src);
        outputStream = new FileOutputStream(dst);
        int readLen = 0;
        byte[] buf = new byte[1024];
        while ((readLen = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, readLen);
        }
        outputStream.flush();
        inputStream.close();
        outputStream.close();
        return true;
    }

    /**
     * @param src
     * @param dst
     * @return
     * @throws IOException
     */
    public static boolean copyFile(String src, String dst) throws IOException {

        return copyFile(new File(src), new File(dst));
    }


    /**
     * 复制整个目录
     *
     * @param srcDir
     * @param destDir
     * @param auto
     * @return
     * @throws IOException
     */
    public static boolean copyFolder(File srcDir, File destDir, boolean auto)
            throws IOException {

        if ((!srcDir.exists())) {
            return false;
        }
        if (srcDir.isFile() || destDir.isFile()) {
            return false;
        }
        if (!destDir.exists()) {
            if (auto) {
                destDir.mkdirs();
            } else {
                return false;
            }
        }
        File[] srcFiles = srcDir.listFiles();
        int len = srcFiles.length;
        for (int i = 0; i < len; i++) {
            if (srcFiles[i].isFile()) {
                File destFile = new File(destDir.getPath() + "//"
                        + srcFiles[i].getName());
                copyFile(srcFiles[i], destFile);
            } else if (srcFiles[i].isDirectory()) {
                File theDestDir = new File(destDir.getPath() + "//"
                        + srcFiles[i].getName());
                copyFolder(srcFiles[i], theDestDir, auto);
            }
        }
        return true;
    }

    /**
     * @param srcDir
     * @param desDir
     * @param auto
     * @return
     * @throws IOException
     */
    public static boolean copyFolder(String srcDir, String desDir, boolean auto)
            throws IOException {

        return copyFolder(new File(srcDir), new File(desDir), auto);
    }

    /**
     * @param srcDir
     * @param desDir
     * @return
     * @throws IOException
     */
    public static boolean copyFolder(File srcDir, File desDir)
            throws IOException {

        return copyFolder(srcDir, desDir, DEFAULT_AUTO_CREATE_DIRECTORY);
    }

    /**
     * @param srcDir
     * @param desDir
     * @return
     * @throws IOException
     */
    public static boolean copyFolder(String srcDir, String desDir)
            throws IOException {

        return copyFolder(srcDir, desDir, DEFAULT_AUTO_CREATE_DIRECTORY);
    }


    /**
     * 移动单个文件
     *
     * @param src
     * @param dst
     * @return
     */
    public static boolean moveFile(File src, File dst) {
        boolean isCopy = false;
        try {
            isCopy = copyFile(src, dst);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (!isCopy) {
            return false;
        }
        deleteFile(src);
        return true;
    }

    /**
     * @param src
     * @param dst
     * @return
     */
    public static boolean moveFile(String src, String dst) {

        return moveFile(new File(src), new File(dst));
    }

    /**
     * 移动整个目录
     *
     * @param srcDir
     * @param destDir
     * @param auto
     * @return
     */
    public static boolean moveFolder(File srcDir, File destDir, boolean auto) {
        if (!srcDir.isDirectory() || !destDir.isDirectory()) {
            return false;
        }
        if (!srcDir.exists()) {
            return false;
        }
        if (!destDir.exists()) {
            if (auto) {
                destDir.mkdirs();
            } else {
                return false;
            }
        }
        File[] srcDirFiles = srcDir.listFiles();
        int len = srcDirFiles.length;
        if (len <= 0) {
            srcDir.delete();
        }
        for (int i = 0; i < len; i++) {
            if (srcDirFiles[i].isFile()) {
                File oneDestFile = new File(destDir.getPath() + "//"
                        + srcDirFiles[i].getName());
                moveFile(srcDirFiles[i], oneDestFile);
            } else if (srcDirFiles[i].isDirectory()) {
                File oneDestFile = new File(destDir.getPath() + "//"
                        + srcDirFiles[i].getName());
                moveFolder(srcDirFiles[i], oneDestFile, auto);
                deleteFolder(srcDirFiles[i]);
            }

        }
        return true;
    }

    /**
     * @param src
     * @param dst
     * @param auto
     * @return
     */
    public static boolean moveFolder(String src, String dst, boolean auto) {
        return moveFolder(new File(src), new File(dst));
    }

    /**
     * @param src
     * @param dst
     * @return
     */
    public static boolean moveFolder(File src, File dst) {
        return moveFolder(src, dst, DEFAULT_AUTO_CREATE_DIRECTORY);
    }

    /**
     * @param src
     * @param dst
     * @return
     */
    public static boolean moveFolder(String src, String dst) {
        return moveFolder(new File(src), new File(dst), DEFAULT_AUTO_CREATE_DIRECTORY);
    }


    /**
     * 获取私有文件目录（/data/data/yourpackage/file)
     *
     * @return
     */
    public static File getPrivateDir() {
        return App.Companion.getContext().getFilesDir();
    }
}
